<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import service from '@/utils/request'
import { ElMessage } from 'element-plus'

const deviceData = ref({
  soil: {
    nitrogen: '0',
    phosphorus: '0',
    potassium: '0',
    temperature: '0',
    moisture: '0',
    conductivity: '0',
    ph: '0',
    illumination: '0',
    co2: '0',
    airTemp: '0',
    airHumidity: '0'
  },
  deviceStatus: {
    soilSensor: 'offline',
    camera: 'offline'
  }
})

const loading = ref(false)

// 手动采集数据
const handleManualCollect = async () => {
  try {
    loading.value = true
    const greenhouseNumber = '300822040454'
    // 调用手动采集接口
    await service.post(`/api/collector/collect/${greenhouseNumber}`)
    ElMessage.success('数据采集成功')
    // 立即刷新数据显示
    await fetchDeviceData()
  } catch (error) {
    console.error('手动采集数据失败:', error)
    ElMessage.error('数据采集失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取设备实时数据
const fetchDeviceData = async () => {
  try {
    const greenhouseNumber = '300822040454'
    const response = await service.get(`/api/sensor-data/greenhouse/${greenhouseNumber}/latest`)
    console.log('设备实时数据:', response)
    
    // 处理返回的数据
    if (response && typeof response === 'object') {
      // 遍历所有设备数据
      Object.values(response).forEach(info => {
        if (info && info.device && info.latestData) {
          const { device, latestData } = info
          
          // 根据设备类型更新对应的数据
          switch (device.category.toLowerCase()) {  // 转换为小写进行比较
            case 'soil_nitrogen':
              deviceData.value.soil.nitrogen = `${latestData.value}mg/kg`
              deviceData.value.deviceStatus.soilSensor = 'online'
              break
            case 'soil_phosphorus':
              deviceData.value.soil.phosphorus = `${latestData.value}mg/kg`
              break
            case 'soil_potassium':
              deviceData.value.soil.potassium = `${latestData.value}mg/kg`
              break
            case 'soil_temperature':
              deviceData.value.soil.temperature = `${latestData.value}°C`
              break
            case 'soil_moisture':
              deviceData.value.soil.moisture = `${latestData.value}%`
              break
            case 'soil_conductivity':
              deviceData.value.soil.conductivity = `${latestData.value}μS/cm`
              break
            case 'soil_ph':
              deviceData.value.soil.ph = latestData.value
              break
            case 'light_intensity':
              deviceData.value.soil.illumination = `${latestData.value}lux`
              break
            case 'soil_co2':
              deviceData.value.soil.co2 = `${latestData.value}ppm`
              break
            case 'air_temperature':
              deviceData.value.soil.airTemp = `${latestData.value}°C`
              break
            case 'air_humidity':
              deviceData.value.soil.airHumidity = `${latestData.value}%`
              break
          }
        }
      })
    }
  } catch (error) {
    console.error('获取设备数据失败:', error)
  }
}

let timer = null

onMounted(() => {
  fetchDeviceData()
  // 每30秒更新一次数据
  timer = setInterval(fetchDeviceData, 30000)
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<template>
  <div class="panel device-monitor">
    <div class="panel-header">
      <span>设备实时监测数据</span>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          :loading="loading"
          @click="handleManualCollect"
        >
          <i class="el-icon-refresh" />
          手动采集
        </el-button>
      </div>
    </div>

    <div class="monitor-content">
      <div class="data-section">
        <h3 class="section-title">土壤监测数据</h3>
        <div class="data-grid">
          <div class="data-item">
            <span class="label">含氮量</span>
            <span class="value">{{ deviceData.soil.nitrogen }}</span>
          </div>
          <div class="data-item">
            <span class="label">含磷量</span>
            <span class="value">{{ deviceData.soil.phosphorus }}</span>
          </div>
          <div class="data-item">
            <span class="label">含钾量</span>
            <span class="value">{{ deviceData.soil.potassium }}</span>
          </div>
          <div class="data-item">
            <span class="label">土壤温度</span>
            <span class="value">{{ deviceData.soil.temperature }}</span>
          </div>
          <div class="data-item">
            <span class="label">含水率</span>
            <span class="value">{{ deviceData.soil.moisture }}</span>
          </div>
          <div class="data-item">
            <span class="label">电导率</span>
            <span class="value">{{ deviceData.soil.conductivity }}</span>
          </div>
          <div class="data-item">
            <span class="label">pH值</span>
            <span class="value">{{ deviceData.soil.ph }}</span>
          </div>
          <div class="data-item">
            <span class="label">光照度</span>
            <span class="value">{{ deviceData.soil.illumination }}</span>
          </div>
          <div class="data-item">
            <span class="label">CO2浓度</span>
            <span class="value">{{ deviceData.soil.co2 }}</span>
          </div>
          <div class="data-item">
            <span class="label">空气温度</span>
            <span class="value">{{ deviceData.soil.airTemp }}</span>
          </div>
          <div class="data-item">
            <span class="label">空气湿度</span>
            <span class="value">{{ deviceData.soil.airHumidity }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.monitor-content {
  padding: 15px;
  overflow-y: auto;
  max-height: calc(100vh - 200px);
}

.section-title {
  color: #30f3f9;
  font-size: 16px;
  margin-bottom: 15px;
  font-weight: normal;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  padding-bottom: 20px;
}

.data-item {
  background: rgba(0,47,167,0.3);
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 5px;
}

.value {
  color: #67e0e3;
  font-size: 16px;
  font-weight: bold;
}

.device-status {
  margin-top: 20px;
}

.status-list {
  display: flex;
  gap: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-name {
  color: #fff;
  font-size: 14px;
}

:deep(.el-tag--success) {
  background: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.2);
}

:deep(.el-tag--danger) {
  background: rgba(245, 108, 108, 0.1);
  border-color: rgba(245, 108, 108, 0.2);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-button--primary) {
  background: rgba(48, 243, 249, 0.2);
  border: 1px solid rgba(48, 243, 249, 0.4);
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background: rgba(48, 243, 249, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(48, 243, 249, 0.2);
}
</style> 